from logging import getLogger

from nevow.athena import LiveElement, expose
from nevow.loaders import stan
from nevow import tags

from zope.component import getGlobalSiteManager

from meercat.harvester.base.interfaces import IHarvester, IQueriableHarvester
from meercat.storage.interfaces import IStorage

from meercat.job.interfaces import IJob



__all__ = ['JobList']

log = getLogger('meercat.server.nevow.elements.job')

registry = getGlobalSiteManager()

class JobList(LiveElement):
    jsClass = u'Meercat.Job.List'
    
    docFactory = stan(tags.div(render=tags.directive('liveElement'))[
        tags.ul(class_='JobListActions actionList')[
            tags.li()[
                tags.a(href='#',
                       onclick="Nevow.Athena.Widget.get(this).addJobTypeForm(); return false;")['Add Job']],
            tags.li()[
                tags.a(href='#',
                       onclick="Nevow.Athena.Widget.get(this).refresh(); return false;")['Refresh List']]],
        tags.ul(class_='JobList')])
    
    @expose
    def getJobs(self):
        log.info('%s.getJobs()' % (str(self),))
        return map(lambda x: '<a href="#" onclick="Nevow.Athena.Widget.get(this).showJobStatus(\'%s\'); return false;">%s</a>' % (x[0],x[0]), registry.getUtilitiesFor(IJob))
    
    @expose
    def getJobStatusElement(self, name):
        log.info('%s.getJobStatusElement(name=%s)' % (str(self),name,))
        from meercat.server.nevow.elements.job.status import JobStatus
        job = registry.getUtility(IJob, name)
        element = JobStatus(job, name)
        element.setFragmentParent(self)
        
        return element
    
    @expose
    def getJobTypeForm(self):
        log.info('%s.getJobTypeForm()' % (str(self),))
        from meercat.server.nevow.elements.job.forms import JobTypeForm
        element = JobTypeForm()
        element.setFragmentParent(self)
        
        return element